import java.io.IOException;
/**
 * Created by IntelliJ IDEA.
 * User: Fatadeild Hagkaups
 * Date: 16.11.2011
 * Time: 23:37
 *
 * Þessi klasi sér um að leika leikinn.
 */

public class Game
{
    /**
     * Meðlimabreytur klasans.
     */

    Board board;
    Input input;

    /**
     * Smiður.
     */
    public Game()
    {
        board = new Board(); // Býr til borð og upphafsstillir það.
        input = new Input(); // Nær í input frá leikmönnum.
    }

    /**
     * Fall sem sér um að leika leikinn.
     */
    public void play()  {

        boolean KeepOnPlaying  = true;

        try
        {
            board.printBoardWithNumbers();
            input.askForName();
        }
        catch(Exception e)
        {
            System.out.println("Something went wrong!");
            System.exit(0);
        }

        // Allt er í lagi, höldum áfram!

        do
        {
            try
            {
                System.out.println("\nRound #" + input.getRound());
                board.printBoard();

                System.out.println(input.checkTurn().getPlayerName() + " (" + input.checkTurn().getMark() + ") should play his/her move! ");

                //Ef að bæta við merki á borðið skilar false, þá er þessi staðsetning upptekin og láta hann gera aftur.
                if(!board.addToBoard(input.getInputFromConsole(), input.checkTurn().getMark()))
                {
                    System.out.println("\nThis place is occupied! Please choose again.");
                    input.setRound(input.getRound()-1);
                }


                if(Check.checkWin(board, input))
                {
                    Player Winner = input.getWinner();
                    System.out.println("\nCONGRATULATIONS " + Winner.getPlayerName() + " - YOU WON!!!!!!!!!");
                    board.printBoard();
                    KeepOnPlaying = input.playAgain();
                    board = new Board();
                    input.newGame();
                }

                else if(Check.checkBoardFull(board))
                {
                    System.out.println("\nNOBODY WON !!!!!!!!!!!");
                    board.printBoard();
                    KeepOnPlaying = input.playAgain();
                    board = new Board();
                    input.newGame();
                }

                input.incRound();
            }
            catch(IOException e)
            {
                System.out.println("Something went wrong!");
                System.exit(0);
            }


        } while(KeepOnPlaying);
    }

}
